package com.jiazhong.schedule.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class CorsFilter implements Filter {

    // 允许的前端源地址
    private String allowedOrigins = "http://localhost:5173";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 可以从web.xml中读取配置参数
        String origins = filterConfig.getInitParameter("cors.allowed.origins");
        if (origins != null && !origins.isEmpty()) {
            allowedOrigins = origins;
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 设置允许的源地址
        httpResponse.setHeader("Access-Control-Allow-Origin", allowedOrigins);

        // 允许携带Cookie
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");

        // 允许的请求方法
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");

        // 允许的请求头
        httpResponse.setHeader("Access-Control-Allow-Headers",
                "Content-Type, X-Requested-With, accept, Origin, Authorization, " +
                        "Access-Control-Request-Method, Access-Control-Request-Headers");

        // 预检请求的缓存时间（秒）
        httpResponse.setHeader("Access-Control-Max-Age", "3600");

        // 处理预检请求（OPTIONS方法）
        if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        // 继续处理其他请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 过滤器销毁时的清理操作
    }
}
